/**  
 * @Title: AdminController.java
 * @Package com.limit.control.admin
 * @author maoyun(maoyun0903@163.com)
 * @date 2014-4-2 下午05:13:02
 * @version V1.0
 */ 
package com.limit.control.admin;

import java.util.Date;
import java.util.List;

import cn.rj.util.security.MD5;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.limit.control.admin.validate.AdminValidator;
import com.limit.model.Actor;
import com.limit.model.Admin;

/** 
 * <br/>
 * @author maoyun(maoyun0903@163.com)
 * @date 2014-4-2 下午05:13:02 
 * @version V1.0
 */

public class AdminController extends BaseController {

	public void index(){
		this._commonSetId();
		this._commonIndex();
	}

	private void _commonIndex() {
		int pageNow = this.getParaToInt("p", 1);
		Page<Admin> admins =  Admin.dao.paginate(pageNow, pageSize, "select *", "from admin where actor_id=?", id);
		this.setAttr("admins", admins);
		this.setAttr("actor_id", id);
		this.render("admins.html"); 
	}
	
	/**
	 * 跳转视图
	 */
	public void view(){
		this._commonSetId();
		Admin admin = new Admin();
		if(id > 0){
			admin = Admin.dao.findById(id);
		}
		List<Actor> actors = Actor.dao.getAllList();
		this.setAttr("actors", actors);
		this.setAttr("admin", admin);
		this.setAttr("actor_id", this.getPara("actor_id"));
		render("admin_view.html");
	}
	
	/**
	 * 添加
	 */
	@Before(AdminValidator.class)
	public void save(){
		Admin admin = this.getModel(Admin.class);
		admin.set("password", MD5.UTF8Encode(admin.getStr("password")))
			 .set("create_time", new Date())
			 .save();
		// 传给index函数需要的角色ID号
		id = this.getParaToLong("actor_id");
		this._commonIndex();
		
	}
	
	/**
	 * 修改
	 */
	public void update(){
		Admin admin = this.getModel(Admin.class);
		String old_password = this.getPara("old_password");
		String new_password = admin.getStr("password");
		//没有修改密码
		if(new_password.trim().equals(old_password)){
			admin.update();
		}else{
			admin.set("password", MD5.UTF8Encode(new_password)).update();
		}
		id = this.getParaToLong("actor_id");
		this._commonIndex();
	}
	
	/**
	 * 禁用
	 */
	public void disable(){
		this._commonSetId();
		Admin.dao.findById(id).set("disable", 1).update();
		this.index();
	}
	
	/**
	 * 解禁
	 */
	public void renew(){
		this._commonSetId();
		Admin.dao.findById(id).set("disable", -1).update();
		this.index();
	}
}
